package cn.zhb.backend.service;

import cn.zhb.backend.annotation.SyncLock;
import cn.zhb.backend.core.converter.UserConverter;
import cn.zhb.backend.core.dto.UserSaveDto;
import cn.zhb.backend.core.entity.User;
import cn.zhb.backend.core.vo.UserVo;
import cn.zhb.backend.exception.ExceptionMessage;
import cn.zhb.backend.exception.SystemException;
import cn.zhb.backend.mapper.UserMapper;
import cn.zhb.backend.repository.UserRepository;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/***
 *@Description
 *@Author ZHB
 *@Create 2025/7/3 下午11:13
 **/
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserConverter userConverter;

    public UserVo login(String account, String password) {
        User user = userRepository.findByAccount(account)
                .orElseThrow(() -> new SystemException(ExceptionMessage.ACCOUNT_NOT_EXIST));

        if (!user.getPassword().equals(password))
            throw new SystemException(ExceptionMessage.PASSWORD_IS_ERROR);
        else return userConverter.poToVo(user);

    }

    @SyncLock
    @Transactional
    public UserVo register(UserSaveDto userSaveDto) {
        User user = userRepository.findByAccount(userSaveDto.getAccount()).orElse(null);

        if(user != null) throw new SystemException(ExceptionMessage.ACCOUNT_IS_EXIST);

        user = userRepository.save(userConverter.saveDtoToPo(userSaveDto));

        return userConverter.poToVo(user);

    }
}
